package howl.Servlets;

import howl.model.Model;
import howl.model.PMF;
import howl.types.HowlUser;
import howl.types.TableDescriptor;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import compiler.exceptions.HowlModelException;

@SuppressWarnings("serial")
public class FeedAccessHowlServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		HowlUser hu = Model.getHowlUserfromUser(user);
		Model m = new Model(hu);
		
		String User = req.getParameter("User");
		String[] Users = User.split("\n");
		String Feed = req.getParameter("Feed");
		

		TableDescriptor td;
		try {
			td = m.getTableDescriptor(Feed);
			for(int i = 0; i<Users.length;i++){
				HowlUser u= Model.getHowlUserfromEmail(Users[i].trim());
				//HowlUser u = getHowlUserfromUser(Users[i].trim());
				if(u != null) {
				m.addAccess(td, u);
				}
				}
				resp.sendRedirect("Auth/index.jsp");
		} catch (HowlModelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	private static HowlUser getHowlUserfromUser(String u) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm
				.newQuery("select from howl.types.HowlUser "
						+ "where emailAddress == Param "
						+ "parameters String Param "
						+ "import howl.types.HowlUser;");
		List<HowlUser> results = (List<HowlUser>) query.execute(u);

		return results.get(0);
	}
}
